<template>
  <div class="login-container">
    <div class="modal">
      <h4>yuCloud</h4>
      <el-form
          ref="ruleFormRef"
          :model="user"
          status-icon
          :rules="rules">
        <el-form-item prop="userName">
          <el-input v-model="user.userName" :prefix-icon="Avatar" type="text" autocomplete="off"/>
        </el-form-item>
        <el-form-item prop="userPwd">
          <el-input
              v-model="user.userPwd"
              :prefix-icon="View"
              type="password"
              autocomplete="off"
          />
        </el-form-item>
        <el-form-item>
          <el-button class="el-button" type="primary" @click="submitForm(ruleFormRef)">登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import {Avatar, View} from "@element-plus/icons-vue";
import {reactive, ref, toRefs} from "vue";
import {useRoute, useRouter} from "vue-router";
import {useStore} from 'vuex'

const ruleFormRef = ref()
const router = useRouter()
const route = useRoute()
const store = useStore()

const state = reactive({
  user: {
    userName: '',
    userPwd: ''
  },
  rules: {
    userName: [
      {required: true, message: '请输入用户名', trigger: 'blur'}
    ],
    userPwd: [
      {required: true, message: '请输入密码', trigger: 'blur'}
    ]
  }
})

const submitForm = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      store.dispatch('users/login', state.user).then(() => {
        router.push({
          path: route.fullPath.split('=')[1] || '/'
        })
      })
    }
  })
}

const {user, rules} = toRefs(state)
</script>

<style lang="scss">
.login-container {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: space-around;
  flex-direction: column;
  align-items: center;

  .modal {
    width: 500px;
    padding: 50px;
    box-shadow: 0 0 3px 0 #c7c7c7;
    border-radius: 10px;

    h4 {
      text-align: center;
      margin-bottom: 20px;
      font-size: 30px;
      font-weight: 500;
    }

    font-weight: 500;
  }

  .el-button {
    width: 100%;
  }
}
</style>
